import styled from "@emotion/styled"
import { useAtom } from "jotai"
import { balanceIconStateAtom } from "../atom"
import { NavLink } from "react-router-dom"

interface BalanceIconProps {
    color: string
    icon: React.ReactNode | string | null
    name: string
    to?: string
}

const IconContainer = styled.div`
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 76rem;
    height: 48rem;
    cursor: pointer;
`

interface IconWrapper {
    color: string
}

const IconWrapper = styled.div<IconWrapper>`
    width: 28rem;
    height: 28rem;
    background-color: ${(props) => props.color}; /* 动态背景色 */
    border-radius: 4rem; /* 圆角 */
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 4rem;
    padding: 5rem;
`

const ButtonIcon = styled.img`
    width: 18rem;
    height: 18rem;
`

const ButtonText = styled.div`
    font-family: Gilroy;
    font-weight: 500;
    font-size: 12rem;
    text-align: center;
`
const StyledNavLink = styled(NavLink)`
    text-decoration: none;
    color: inherit;
    display: flex;
    align-items: center;
    cursor: pointer;
`

const CustomIconButton: React.FC<BalanceIconProps> = ({ color, icon, name, to }) => {
    const [buttonState, setButtonState] = useAtom(balanceIconStateAtom)

    // 点击处理函数
    const handleClick = () => {
        setButtonState({ name, clicked: true })
    }

    const renderIcon = () => {
        if (typeof icon === "string") {
            return <ButtonIcon src={icon} />
        }
        if (typeof icon === "object" && icon !== null) {
            return icon as React.ReactElement
        }
        return null
    }

    return (
        <>
            {to ? (
                <StyledNavLink to={to}>
                    <IconContainer onClick={handleClick}>
                        <IconWrapper color={color}>{renderIcon()}</IconWrapper>
                        <ButtonText>{name}</ButtonText>
                    </IconContainer>
                </StyledNavLink>
            ) : (
                <IconContainer onClick={handleClick}>
                    <IconWrapper color={color}>{renderIcon()}</IconWrapper>
                    <ButtonText>{name}</ButtonText>
                </IconContainer>
            )}
        </>
    )
}

export default CustomIconButton
